package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private UserService userService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 再来一单
     * @param orders
     * @return
     */
    @PostMapping("/again")
    public R<List<ShoppingCart>> again(@RequestBody Orders orders) {
        Long ordersId = orders.getId();
        LambdaQueryWrapper<OrderDetail> orderDetailWrapper = new LambdaQueryWrapper<>();
        orderDetailWrapper.eq(ordersId != null, OrderDetail::getOrderId, ordersId);
        List<OrderDetail> orderDetailList = orderDetailService.list(orderDetailWrapper);
        //设置用户id，指定当前是哪个用户的购物车数据
        Long currentId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> shoppingCartWrapper = new LambdaQueryWrapper<>();
        shoppingCartWrapper.eq(ShoppingCart::getUserId, currentId);
        shoppingCartService.remove(shoppingCartWrapper);
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setName(orderDetail.getName());
            shoppingCart.setImage(orderDetail.getImage());
            shoppingCart.setUserId(currentId);
            if (orderDetail.getDishId() != null) {
                Dish dish = dishService.getById(orderDetail.getDishId());
                if (dish.getStatus() == 1) {
                    shoppingCart.setDishId(orderDetail.getDishId());
                } else {
                    throw new CustomException("该购物车里有商品已经停售");
                }
            }
            if (orderDetail.getSetmealId() != null) {
                Setmeal setmeal = setmealService.getById(orderDetail.getSetmealId());
                if (setmeal.getStatus() == 1) {
                    shoppingCart.setSetmealId(orderDetail.getSetmealId());
                } else {
                    throw new CustomException("该购物车里有商品已经停售");
                }
            }
            shoppingCart.setDishFlavor(orderDetail.getDishFlavor());
            shoppingCart.setNumber(orderDetail.getNumber());
            shoppingCart.setAmount(orderDetail.getAmount());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());
        shoppingCartService.saveBatch(shoppingCartList);
        return R.success(shoppingCartList);
    }


    /**
     * 更改订单状态
     *
     * @param orders
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Orders orders) {
        orderService.updateById(orders);
        return R.success("操作成功。");
    }

    /**
     * 后台系统展示订单信息
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page<OrdersDto>> showOrder(Integer page, Integer pageSize, String number, String beginTime, String endTime) {
        log.info("当前页页码：{} 每页显示条数：{}", page, pageSize);
        //创建Orders分页对象
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        //设置查询条件
        LambdaQueryWrapper<Orders> ordersWrapper = new LambdaQueryWrapper<>();
        //根据结账时间倒序排序
        ordersWrapper.orderByDesc(Orders::getCheckoutTime)
                .like(number != null, Orders::getNumber, number)
                .between(!(beginTime == null && endTime == null), Orders::getOrderTime, beginTime, endTime);
        //分页查询订单信息
        orderService.page(ordersPage, ordersWrapper);
        //创建OrdersDto分页对象
        Page<OrdersDto> ordersDtoPage = new Page<>();
        //把ordersPage对象的信息（除了records内容）复制到ordersDtoPage对象中
        BeanUtils.copyProperties(ordersPage, ordersDtoPage, "records");
        //使用stream流转换为所需数据
        List<OrdersDto> list = ordersPage.getRecords().stream().map(orders -> {
            //创建一个ordersDto对象
            OrdersDto ordersDto = new OrdersDto();
            //将orders对象的信息拷贝到ordersDto中
            BeanUtils.copyProperties(orders, ordersDto);
            //创建条件构造器对象
            LambdaQueryWrapper<OrderDetail> orderDetailWrapper = new LambdaQueryWrapper<>();
            //设置条件：与当前订单id一致
            orderDetailWrapper.eq(OrderDetail::getOrderId, orders.getId());
            //通过条件查询所有的订单详情
            List<OrderDetail> orderDetails = orderDetailService.list(orderDetailWrapper);
            //把详情放入ordersDto对象中
            ordersDto.setOrderDetails(orderDetails);

            User user = userService.getById(orders.getUserId());
            ordersDto.setUserName(user.getName());

            return ordersDto;
        }).collect(Collectors.toList());
        //把新的records设置到ordersDtoPage分页信息中
        ordersDtoPage.setRecords(list);
        //返回结果
        return R.success(ordersDtoPage);
    }

    /**
     * 展示订单
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page<OrdersDto>> showAppOrder(Integer page, Integer pageSize) {
        log.info("当前页页码：{} 每页显示条数：{}", page, pageSize);
        //创建Orders分页对象
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        //设置查询条件
        LambdaQueryWrapper<Orders> ordersWrapper = new LambdaQueryWrapper<>();
        Long userCurrentId = BaseContext.getCurrentId();
        //根据结账时间倒序排序
        ordersWrapper.eq(userCurrentId != null, Orders::getUserId, userCurrentId)
                .orderByDesc(Orders::getCheckoutTime);
        //分页查询订单信息
        orderService.page(ordersPage, ordersWrapper);
        //创建OrdersDto分页对象
        Page<OrdersDto> ordersDtoPage = new Page<>();
        //把ordersPage对象的信息（除了records内容）复制到ordersDtoPage对象中
        BeanUtils.copyProperties(ordersPage, ordersDtoPage, "records");
        //使用stream流转换为所需数据
        List<OrdersDto> list = ordersPage.getRecords().stream().map(orders -> {
            //创建一个ordersDto对象
            OrdersDto ordersDto = new OrdersDto();
            //将orders对象的信息拷贝到ordersDto中
            BeanUtils.copyProperties(orders, ordersDto);
            //创建条件构造器对象
            LambdaQueryWrapper<OrderDetail> orderDetailWrapper = new LambdaQueryWrapper<>();
            //设置条件：与当前订单id一致
            orderDetailWrapper.eq(OrderDetail::getOrderId, orders.getId());
            //通过条件查询所有的订单详情
            List<OrderDetail> orderDetails = orderDetailService.list(orderDetailWrapper);
            //把详情放入ordersDto对象中
            ordersDto.setOrderDetails(orderDetails);
            return ordersDto;
        }).collect(Collectors.toList());
        //把新的records设置到ordersDtoPage分页信息中
        ordersDtoPage.setRecords(list);
        //返回结果
        return R.success(ordersDtoPage);
    }

    /**
     * 用户下单
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        log.info("订单数据：{}", orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }
}